package cn.st4rlight.util.string;

import java.lang.reflect.Field;
import java.util.Objects;

import cn.st4rlight.util.exception.ServiceException;

/**
 * 用于一些需要trim的场景
 *
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-05-04
 */
public interface Trimmable {

    /**
     * 对所有String类型字段做一次trim，兼容null
     */
    default void trim() {
        for (Field field : this.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
                Object value = field.get(this);
                if (Objects.nonNull(value) && value instanceof String) {
                    field.set(this, ((String) value).trim());
                }
            } catch (Exception ex) {
                throw ServiceException.of(ex);
            }
        }
    }
}
